import React from 'react';
import {
  View,
  Text,
  TextInput,
  TouchableOpacity,
  ListView,
  Keyboard,
  Platform,
} from 'react-native';

import Config from '../../config';
import DataManager from '../../datas/DataManager';
import ResponseConstants from '../../common/ResponseConstants';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import ToastUtils from '../../common/ToastUtils';
import {DateUtils} from '../../utils/Utils';
import CommonChatItemView from '../common/CommonChatItemView';
import CommonInputBarView from '../common/CommonInputBarView';
import BasePage from '../common/BasePage';
import LoginCheckIsUserAction from '../../actions/login/LoginCheckIsUserAction';
import IMSingleLinker from '../../datas/im/IMSingleLinker';
import IMConstants from './IMConstants';

//显示pullToLoadMore
const SHOW_PULL_LOADMORE_OFFSET_Y = -50;
//显示releaseToLoadMore
const SHOW_RELEASE_LOADMORE_OFFSET_Y = -100;
//头部加载显示的高度
const HEADER_HEIGHT = 140;

export default class IMOne2OnePage extends BasePage {
  constructor(props) {
    super(props);

    this._listView = null;
    this._ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this._data = null;
    this._requestTimer = null;
    this._isDraging = false;
    this._viewWidth = SizeUtils.getWindowSize().width;
    this._inputBar = null;

    this.state.behavior = "padding";
    this.state.dataSource = this._ds.cloneWithRows([]);
    this.state.refreshTitle = "";
    this.state.loadMoreTitle = "";
    this.state.loadMoreStatus = IMConstants.LoadMoreStatus.no;
    this.state.keyboardHeight = 0;

    this._saveListLayout = null;
    this._offsetY = 0;
    this._saveListViewContentHeight = 0;
    this._isAtEnd = true;
    this._itemViewRefs = [];
    this._loadMoreMarkForSizeChange = false;
    // this._isFirstChangeVisible = true;
  }

  componentDidMount() {
    this._initData();
    this._delayRequestData();
    this._requestUserData();

    this._keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow.bind(this));
    this._keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));

    if(Platform.OS === "ios") {
      this._keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide.bind(this));
    }
    else{
      this._keyboardWillHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardWillHide.bind(this));
    }
    this._keyboardDidChangeListener = Keyboard.addListener('keyboardDidChangeFrame', this._keyboardDidChange.bind(this));
  }

  componentWillUnmount() {
    this._keyboardWillShowListener.remove();
    this._keyboardDidShowListener.remove();
    this._keyboardWillHideListener.remove();
    this._keyboardDidChangeListener.remove();
    this._itemViewRefs = null;

    this._clearRequestTimer();
  }

  _initData() {
    this._initLinker();
    this._isAtEnd = true;
    this._offsetY = 0;
    this._isFirstChangeVisible = true;
    this._data = this._linker === undefined ? [] : this._linker.getDatas();
    let dataSource = this._ds.cloneWithRows(this._data);
    this.state.dataSource = dataSource;
  }

  _initLinker() {
    let talkerId = 0;
    this._linker = DataManager.callMethod(Constants.MODULE_TYPE.IM, "getLinker",
      [IMConstants.linkerType.one2one, talkerId,
        IMSingleLinker, {linkerType:IMConstants.linkerType.one2one,}]);
    this._linker.init({sendMessageCall:this._sendMessageCall.bind(this),
      updateCall:this._onLinkerUpdateCall.bind(this)});
  }

  _dealEnterPage() {
    this._initData();
    this._delayRequestData();
    this._requestUserData();
  }

  _requestUserData() {

  }

  _dealLeavePage() {
    this._dealData([]);
    if(this._linker) {
      this._linker.dispose();
      this._linker = null;
    }
    this._itemViewRefs = [];
  }

  _getUserData() {
    return this.props.pageData.routeData;
  }

  _dealData(data) {
    this._data = data;
    let dataSource = this._ds.cloneWithRows(this._data);
    this.setState({
      dataSource:dataSource,
    })
  }

  _delayRequestData() {
    this._clearRequestTimer();
    this._requestTimer = setTimeout(()=>{
     clearTimeout(this._requestTimer);
     this._requestData();
    }, 500);
  }

  _requestData(loadMore) {
    if(this._linker) {
      this._dealRequestData(loadMore);
    }
  }

  _dealRequestData(loadMore) {
    let result = this._linker && this._linker.requestData(loadMore);
    if(result) {
      this._loadMoreMarkForSizeChange = loadMore;
    }
  }

  _clearRequestTimer() {
    this._requestTimer && clearTimeout(this._requestTimer);
  }

  _onLinkerUpdateCall(data, isSucceed, isLoadMore) {
    if(this.state.loadMoreStatus === IMConstants.LoadMoreStatus.loadMoring) {
      this.setState({
        loadMoreStatus:IMConstants.LoadMoreStatus.no,
      })
    }
    this._dealData(data);
  }

  _sendMessageCall(result, status = 0) {
    if(result) {
      this._dealSendMessageSuccess();
    }
    else {
      if(status === ResponseConstants.status_noData) {
        ToastUtils.show("此用户不存在");
      }
      else {
        let statusStr = status === 0 ? "" : status;
        ToastUtils.show("发送失败" + statusStr);
      }
    }
  }

  _dealSendMessageSuccess() {
    this._inputBar.reset();
  }

  //  ListView的高度发生变化
  _listViewLayout(event) {
    console.log("_listViewLayout", event.nativeEvent);
    if(this._saveListLayout != null) {
      //视图在底部时，保持底部
      if(this._isAtEnd === true) {
        this._saveListLayout = event.nativeEvent.layout;
        this._scrollToEnd();
      }
      else {
        let disHeight = event.nativeEvent.layout.height - this._saveListLayout.height;
        let offsetY = this._offsetY - disHeight;
        this._saveListLayout = event.nativeEvent.layout;
        this._scrollTo(offsetY);
      }
    }
    else {
      this._saveListLayout = event.nativeEvent.layout;
    }
  }

  //  ListView里面的内容发生变化
  _onlistViewContentSizeChange(width, height) {
    console.log("_onlistViewContentSizeChange", height);
    let disHeight = height - this._saveListViewContentHeight;
    this._saveListViewContentHeight = height;
    //视图在底部时，保持底部
    if(this._isAtEnd === true) {
      this._scrollToEnd(false);
    }
    //不在底部时，保持当前位置不动(上方增加内容，下方增加内容两种情况)

    //加载更早的数据成功——上方增加内容
    else {
    // else if(this._loadMoreMarkForSizeChange === true){
      // let offsetY = this._offsetY + disHeight;
      // this._scrollTo(offsetY, false);
      // this._loadMoreMarkForSizeChange = false;
    }
  }

  _onListChangeVisibleRows(visibleRows, changedRows) {
    // console.log(visibleRows, changedRows);
    for (var i = 1; i < this._itemViewRefs.length; i++) {
      this._itemViewRefs[i].setVisible(visibleRows.s1[i] != undefined);
    }
    //dataType = "top" 从顶部显示出来,则加载更早的数据
    if(visibleRows.s1 && changedRows.s1 && visibleRows.s1[0] != undefined && changedRows.s1[0] != undefined) {
      // if(this._isFirstChangeVisible === true) {
        // this._isFirstChangeVisible = false;
        // return;
      // }
      console.log("顶部出现，加载更早数据...");
      this._requestData(true);
    }
  }

  _scrollTo(offsetY, animated = true) {
    if(offsetY + this._saveListLayout.height > this._saveListViewContentHeight) {
      offsetY = this._saveListViewContentHeight - this._saveListLayout.height;
    }
    if(offsetY < 0) {
      offsetY = 0;
    }
    if(this._offsetY != offsetY) {
      this._listView.scrollTo({y:offsetY, animated:animated});
    }
  }

  _scrollToEnd(animated = true) {
    if(this._saveListLayout != null) {
      let offsetY = this._saveListViewContentHeight - this._saveListLayout.height;
      this._scrollTo(offsetY, animated);
    }
  }

  _keyboardWillShow(e){
      this._setKeyboradHeight(e.endCoordinates.height);
  }

  _keyboardDidShow(e) {
      this._setKeyboradHeight(e.endCoordinates.height, 1);
  }

  _keyboardWillHide(e){
      this._setKeyboradHeight(0);
  }

  _keyboardDidChange(e) {
    // ToastUtils.show("键盘高度改变:" + e.endCoordinates.height);
  }

  _setKeyboradHeight(height, duration = 250){
      this.setState({
          keyboardHeight:height
      })
      // ToastUtils.show("键盘高度:" + height);
  }

  _onRenderItem(data, index) {
    if(data.dataType == "top") {
      return (
        <View style={{width:this._viewWidth, height:SizeUtils.translateDesignHeightToCode(50),
            backgroundColor:"#cccccc00"}}>
        </View>
      )
    }
    return this._dealRenderItem(data, index);
  }

  _dealRenderItem(data, index) {
    return <CommonChatItemView data={data} selfData={this._getUserData().userData}
      userData={this._getUserData()} index={index}
      ref={(ref) => this._itemViewRefs[index] = ref}/>
  }

  _dealRender() {
    return(
      <View style={{width:SizeUtils.getWindowSize().width,
          height:SizeUtils.getWindowSize().height}}>
          <View style={{width:SizeUtils.getWindowSize().width,
            height:SizeUtils.getWindowSize().height - this.state.keyboardHeight,
            paddingTop:Config.paddingTop}} >
            <ListView style={{flex:1,
                // width:SizeUtils.getWindowSize().width,
                // height:SizeUtils.getWindowSize().height - Config.paddingTop - SizeUtils.translateDesignHeightToCode(100),
                backgroundColor:"#ffffff",
                paddingBottom:SizeUtils.translateDesignHeightToCode(20)}}
              ref={(ref)=>{this._listView = ref}}
              enableEmptySections={true}
              scrollEventThrottle={60}
              onScroll={this._onListViewScroll.bind(this)}
              onScrollBeginDrag={(event)=>this._onListViewScrollBeginDrag(event)}
              onScrollEndDrag={(event)=>this._onListViewScrollEndDrag(event)}
              onEndReachedThreshold={1}
              overScrollMode={"always"}
              // onEndReached={(event)=>this._onEndReached(event)}
              dataSource={this.state.dataSource}
              onContentSizeChange = {this._onlistViewContentSizeChange.bind(this)}
              onLayout = {this._listViewLayout.bind(this)}
              // renderHeader={this._onRenderHeader.bind(this)}
              renderRow={this._onRenderItem.bind(this)}
              onChangeVisibleRows={this._onListChangeVisibleRows.bind(this)}
              showsHorizontalScrollIndicator={false}  // 隐藏水平指示器
              showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
              automaticallyAdjustContentInsets = {false}
              // keyboardDismissMode = {"on-drag"}//当拖拽开始的时候隐藏软键盘
              initialListSize={20}
              scrollRenderAheadDistance={20}
              keyboardShouldPersistTaps={"never"}
            />
            {this._renderInputBar()}
          </View>
          {this._renderNavigationBar()}
          {/* {this._renderLoadMore()} */}
      </View>
    )
  }

  _renderInputBar() {
    if(this._showInputBar != false) {
      return (
        <CommonInputBarView style={{width:SizeUtils.getWindowSize().width}}
          ref={(ref) => this._inputBar = ref}
          onSend={this._onSend.bind(this)}/>
      )
    }
  }

  _onRenderHeader() {
    if(this.state.loadMoreStatus === IMConstants.LoadMoreStatus.loadMoring) {
      return (
        <View style={{width:this._viewWidth,
            height:SizeUtils.translateDesignHeightToCode(HEADER_HEIGHT),
            backgroundColor:"#00000000"}}>
        </View>
      )
    }
  }

  _renderLoadMore() {
    if(this.state.loadMoreStatus != IMConstants.LoadMoreStatus.pullToLoadMore
        || this.state.loadMoreStatus != IMConstants.LoadMoreStatus.releaseToLoadMore) {
      return;
    }
    return (
      <View style={{width:this._viewWidth,
          height:SizeUtils.translateDesignHeightToCode(HEADER_HEIGHT),
          position:"absolute",
          justifyContent:"center",
          top:SizeUtils.translateDesignHeightToCode(HEADER_HEIGHT),
          alignItems:"center", backgroundColor:"#00000000", borderWidth:0}}>
        <Text style={{color:"#373737",
          width:this._viewWidth,
          textAlign:"center",
          backgroundColor:"#00000000", borderWidth:0}}>
          {this.state.loadMoreStatus > -1 ? this.state.loadMoreTitle : ""}
        </Text>
      </View>
    )
  }

  _onListViewScrollBeginDrag(event) {
    this._isDraging = true;
    Keyboard.dismiss();
  }

  _onListViewScrollEndDrag(event) {
    if(this._isDraging === true) {
      if(this.state.loadMoreStatus === IMConstants.LoadMoreStatus.releaseToLoadMore) {
        this.setState({
          loadMoreStatus:IMConstants.LoadMoreStatus.loadMoring,
          loadMoreTitle:IMConstants.LoadMoreTitle.loadMoring,
        })
        this._requestData(true);
      }
      else {
        this.setState({
          loadMoreStatus:IMConstants.LoadMoreStatus.no,
          loadMoreTitle:IMConstants.LoadMoreTitle.no,
        })
      }
    }
    this._isDraging = false;
  }

  _onListViewScroll(event){
    this._offsetY = event.nativeEvent.contentOffset.y;
    if(this._linker != undefined) {
      this._linker.saveOffsetY = this._offsetY;
    }
    // console.log("_onListViewScroll", this._offsetY);
    this._setLoadMoreStatus();
  }

  _setLoadMoreStatus() {
    if(this._isDraging === false) {
      return;
    }
    //释放 加载更多
    if(this._offsetY < SHOW_RELEASE_LOADMORE_OFFSET_Y) {
      this.setState({
        loadMoreStatus:IMConstants.LoadMoreStatus.releaseToLoadMore,
        loadMoreTitle:IMConstants.LoadMoreTitle.releaseToLoadMore,
      });
    }
    //下拉 加载更多
    else if(this._offsetY < SHOW_PULL_LOADMORE_OFFSET_Y) {
      this.setState({
        loadMoreStatus:IMConstants.LoadMoreStatus.pullToLoadMore,
        loadMoreTitle:IMConstants.LoadMoreTitle.pullToLoadMore,
      });
    }
    else {
      this.setState({
        loadMoreStatus:IMConstants.LoadMoreStatus.no,
        loadMoreTitle:IMConstants.LoadMoreTitle.no,
      });
    }

    //-50是为了容一下错
    if(this._offsetY + this._saveListLayout.height >= this._saveListViewContentHeight - SizeUtils.translateDesignHeightToCode(50)) {
      this._isAtEnd = true;
    }
    else {
      this._isAtEnd = false;
    }
  }

  _onSend(comment) {
    if(this._linker) {
      this._inputBar.reset();
      this._linker.sendMessage(comment);
    }
    else {
      ToastUtils.show("数据加载中...");
    }
  }
}
